package cn.ad.server.web.filter.bid;

import cn.ad.server.web.spring.service.actions.context.BidContext;
import cn.ad.server.domain.ad.Creative;
import cn.ad.server.domain.ad.InteractionApp;
import cn.ad.server.domain.ad.InteractionRedirects;
import cn.ad.server.domain.ad.Strategy;

import java.util.ArrayList;
import java.util.List;

/**
 * 判断该策略下是否有符合要求的创意。
 * 
 * @author wangwei
 *
 */
public class CreativeInteractionMatcher implements BidMatcherChain {

	@Override
	public boolean match(Strategy strategy, BidContext context) {
		int os = context.getOs();// 得到设备的os
		if (os == 0) {// 如果得不到有效的os,从广告中获取。
			os = context.getSecondOs();
		}
		if (os == 0) {// 广告中获取的os也是无效的。则不出广告。
			return false;
		}

		List<Creative> creatives = strategy.getCreatives();
		List<Creative> matchCreatives = new ArrayList<>();
		for (int i = 0; i < creatives.size(); i++) {
			Creative creative = creatives.get(i);
			int interactionType = creative.getInteractionType();
			if (interactionType == 2) {// 下载。
				InteractionApp interactionApp = creative.getInteractionApp();
				if (interactionApp == null || interactionApp.getAppType() != os) {
					// 设备的os
					// 和
					// appType
					// 匹配。
					continue;
				}
				if (os == 2) {
					String targetOrDownloadUrl = interactionApp.getDownloadUrl();
					if (!targetOrDownloadUrl.startsWith("https:")) {
						continue;
					}
				}
			}
			
			if (interactionType == 1) {
				InteractionRedirects interactionRedirects = creative.getInteractionRedirects();
				if (os == 2) {
					String targetOrDownloadUrl = interactionRedirects.getTargetUrl();
					if (!targetOrDownloadUrl.startsWith("https:")) {
						continue;
					}
				}
			}
			matchCreatives.add(creative);
		}
		strategy.setMatchCreatives(matchCreatives);
		if (matchCreatives.size() == 0) {// 判断是否有匹配的creative
			return false;
		}
		return true;
	}

}
